package org.wedding.system.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.wedding.center.util.QiniuUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhaoyongke
 * @create: 2024-05-30 08:54
 * @description: 微信
 */
public class WxUtils {

    private static String xcx_appId = "wx6ed39b6391783c6e";
    private static String xcx_secretKey = "f88470d65eb1ab69189d32f1d432aef0";

    // 微信小程序 拿code 换取openid
    public static Map<String, String> getWxOpenId(String code,String xcx_appId,String xcx_secretKey ) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        // 请求微信服务器，获取用户 oppenid

        // 微信url
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + xcx_appId + "&secret=" + xcx_secretKey + "&js_code=" + code + "&grant_type=authorization_code";
        //客户端
        OkHttpClient client = new OkHttpClient();
        //用url发起请求
        Request request = new Request.Builder().url(url).build();
        //拿到响应
        Response response = client.newCall(request).execute();
        //如果响应成功，打印返回值
        if (response.isSuccessful()) {
            String body = response.body().string();
            JSONObject jsonObjectResult = JSON.parseObject(body,JSONObject.class);
            Object openid = jsonObjectResult.get("openid");
            Object sessionKey = jsonObjectResult.get("session_key");
            Object unionid = jsonObjectResult.get("unionid");
            System.out.println("openId:::" + openid + "session_key:" + sessionKey + "unionId:" + unionid);
            System.out.println("微信code：：：：" + code + "微信openid：" + body + "微信url：" + url);
            map.put("openId", openid.toString());
            map.put("sessionKey", sessionKey.toString());
            map.put("unionId", "");
            return map;
        }
        return map;
    }

    /**
     * 获取access_token
     * @param appid
     * @param secret
     * @return
     */
    public static String getAccessToken(String appid,String secret){
        try {
            //先根据appId和appSecret获取accessToken
            String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, secret);
            String accessToken = String.valueOf(JSON.parseObject(HttpUtil.get(tokenUrl)).get("access_token"));
            return accessToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static InputStream getMiniProgramCode(String accessToken, String invitedCode){
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));

            // 构建请求JSON数据
            JSONObject requestData = new JSONObject();
            requestData.put("scene", "invitedCode="+invitedCode);
            requestData.put("page", "pages/login");
            requestData.put("check_path", false);
            requestData.put("env_version", "trial");
//        requestData.put("env_version", "release");
            writer.write(requestData.toString());
            writer.flush();
            writer.close();
            InputStream inputStream = connection.getInputStream();

//            BufferedImage bufferedImage = ImageIO.read(inputStream);
//            ImageIO.write(bufferedImage, "jpg", new File(ercodeImage));
//            String encode = Base64.encode(inputStream);
            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static String getPhoneNumber(String phoneCode,String appid,String secret){
        try {
            //先根据appId和appSecret获取accessToken
            String accessToken = getAccessToken(appid,secret);
            //通过token和code来获取用户手机号
            String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?code=%s&access_token=%s", phoneCode, accessToken);
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("code", phoneCode);

            HttpHeaders headers = new HttpHeaders();
            HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
            Object body = response.getBody();
            // 解析JSON字符串s
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
            cn.hutool.json.JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
            String phoneNumber = phoneInfo.getStr("phoneNumber");
            System.out.println("微信小程序获取手机号: " + phoneNumber);
            if (StrUtil.isNotEmpty(phoneNumber)) {
                return phoneNumber;
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}
